package com.MedDroid.task;

import android.content.Intent;
import android.os.AsyncTask;
import com.MedDroid.MainApp;
import com.MedDroid.activity.UserListActivity;
import com.MedDroid.activity.ViewProfileActivity;
import com.MedDroid.control.AuthenticationControl;
import com.MedDroid.control.DatabaseControl;
import com.MedDroid.entities.Permissions;
import com.MedDroid.entities.User;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Romen
 * Date: 02/12/13
 * Time: 11:07 PM
 * Description:
 */
public class LoadUserListTask extends AsyncTask<Void, Void, ArrayList<Integer>>
{
	AuthenticationControl AuthenticationC;
	DatabaseControl DatabaseC;
	WeakReference<UserListActivity> UserListPage;

	public LoadUserListTask(AuthenticationControl Auth, DatabaseControl Data, UserListActivity activity)
	{
		AuthenticationC = Auth;
		DatabaseC = Data;
		UserListPage = new WeakReference<UserListActivity>(activity);
	}

	@Override
	protected ArrayList<Integer> doInBackground(Void... voids)
	{
		return AuthenticationC.getAccess().getUserAccess();
	}

	@Override
	protected void onPostExecute(ArrayList<Integer> List)
	{
		UserListActivity Page = UserListPage.get();
		//Add list
		if (List.size() > 1)
		{
			MainApp.log(Permissions.buildUserAccessString(AuthenticationC.getAccess()));
			Page.ListNames = new ArrayList<String>();
			Page.ListUserId = List;
			for (Integer I : List)
			{
				Page.ListNames.add(DatabaseC.findUser(User.UserIDStr,Integer.toString(I)).getFullName());
			}
			Page.makeList();
		}
		else if (List.size() == 1)
		{
			//TODO Change to allow back button to go to Main Menu instead
			Intent intent = new Intent(Page, ViewProfileActivity.class);
			intent.putExtra("UserID", List.get(0));
			Page.startActivity(intent);
		}
		else
		{
			//TODO Change to allow back button to go to Main Menu instead
			Intent intent = new Intent(Page, ViewProfileActivity.class);
			intent.putExtra("UserID", AuthenticationC.getLoginUser().getUserID());
			Page.startActivity(intent);
		}
	}
}
